Input: Given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
Input & Output Illustration (open for understanding)
var addTwoNumbers = function(l1, l2) {
let carry = 0,
sum = 0;
let runningNode = new ListNode(0, null);
let headNode = runningNode;
while (l1 !== null || l2 !== null) {
sum = l1 != null ? l1.val : 0 + l2 != null ? l2.val : 0 + carry;
carry = 0;
// Error is in below line it states "TypeError: Cannot set properties of undefined (setting 'next')"
runningNode.next = ListNode(sum % 10, null)
runningNode = runningNode.next;
//How to fix it?
if (l1) {
l1.next;
}
if (l2) {
l2.next;
}
}
if (carry) {
runningNode.next = ListNode(carry);
}
return headNode;
};
Several issues:
When calling the constructor, new is needed, otherwise this is undefined and references like this.next are invalid. This correction is needed at two places in your code.
In the assignment to sum, the + operator has precedence over the ? : operator, but in your case you want it the other way, so you need to add parentheses.
The carry is never set to anything else than 0. It should get 1 when the sum is greater than 9.
The final result will always return a list that starts with 0, which is a dummy node that head refers to. This makes the result ten times too large. Return the next node.
Corrected code:
var addTwoNumbers = function(l1, l2) {
let carry = 0,
sum = 0;
let runningNode = new ListNode(0, null);
let headNode = runningNode;
while (l1 !== null || l2 !== null) {
// Use parentheses to make sure the addition happens last:
sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;
// Need to set carry
carry = Math.floor(sum / 10);
// Need "new" when calling constructor
runningNode.next = new ListNode(sum % 10, null);
runningNode = runningNode.next;
// Must assign!
if (l1) {
l1 = l1.next;
}
if (l2) {
l2 = l2.next;
}
}
if (carry) {
// Must call with "new":
runningNode.next = new ListNode(carry);
}
return headNode.next; // skip the zero node
};